package com.hg.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hg.common.BaseContext;
import com.hg.common.HttpStatus;
import com.hg.common.R;
import com.hg.pojo.Admin;
import com.hg.pojo.HgUser;
import com.hg.service.HgUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class HgUserController {

    @Autowired
    private HgUserService hgUserService;
    @PostMapping("/Hg")
    @CrossOrigin
    public R<HgUser> login(@RequestBody Admin admin,HttpServletRequest request){
        System.out.println(admin);
        //0.从session中获取验证码
       /* String da
            //验证码匹配不成功直接退出
            return R.error(HttpStatus.CODE_ERROR,"验证码错误");
        }*/
        String password = admin.getPassword();

        //1、将页面提交的密码password进行md5加密处理
        password = DigestUtils.md5DigestAsHex("123456".getBytes());
        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<HgUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HgUser::getUsername, "admin");
        HgUser user = hgUserService.getOne(queryWrapper);
        //3、如果没有查询到则返回登录失败结果
        if (user == null){
            return R.error(HttpStatus.LOGIN_ERROR,"登录失败");
        }
        //4、密码比对，如果不一致则返回登录失败结果
        if (!user.getPassword().equals(password)){
            return R.error(HttpStatus.LOGIN_ERROR,"登录失败");
        }
        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (user.getStatus() == 0){
            return R.error(HttpStatus.LOGIN_ERROR,"账号已禁用");
        }
        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("hgUser", user.getId());
        BaseContext.setCurrentId(user.getId());
        return R.success();
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中当前id
        request.getSession().removeAttribute("hgUser");
        return R.success(HttpStatus.LOGOUT_SUCCESS,"退出成功");
    }

    @GetMapping("/page")
    public Page<HgUser> page(int currentPage,int pageSize){
        System.out.println(currentPage);
        System.out.println(pageSize);
        Page<HgUser> pageInfo = new Page<>(currentPage,pageSize);

        hgUserService.page(pageInfo);
       /* pageInfo.setTotal(pageInfo.getRecords().size());
*/
        return pageInfo;
    }

}